/**
 * 数组转树
 * @param items
 * @param nodeType
 * @param id
 */
export function arrayToTree(items: any, nodeType: "company" | "group", id?: number) {
    const rootItems = items.filter(item => nodeType === "company"? item.id === id : !item.parentId)
    function childrenOf(parentId: any){
        const children = items.filter(item => item.parentId === parentId)
        children.forEach(child => {
            if (childrenOf(child.id).length) {
                child.children = childrenOf(child.id)
            }
        })
        return children;
    }
    rootItems.forEach(item => {
        item.children = childrenOf(item.id);
    })
    return rootItems;
}

/**
 * 数组插入到树形中
 * @param tree
 * @param array
 */
export function insertArrayIntoTree(tree, array) {
    tree.forEach(item =>{
        traverseTree(item)
    })

    function traverseTree(tree) {
        const groups = array.filter(item => item.deptId === tree.id)

        if(groups.length){
            tree.children.push(...groups)
        }
        // 递归遍历所有子节点
        if (tree.children) {
            tree.children.forEach(child => {
                if(child.nodeType === "company"){
                    traverseTree(child);
                }
            })
        }
    }
}


export function initDictionary(data1, data2){

    let groupDictionary = {}
    // 设备索引位置
    let deviceGroupDict = {}
    // 各分组下记录设备的增长情况
    let deviceGroup = {}
    // 设备nodeId在各组下分布情况
    let deviceNodeIdGroup = {}

    initializeTheCompanyGroupDictionary(data1)

    // console.log(groupDictionary)
    initializeTheDeviceDictionary()
    // console.log(deviceGroupDict, deviceGroup, deviceNodeIdGroup)

    /**
     * 初始化公司和组别的索引字典
     * @param data
     * @param level
     */
    function initializeTheCompanyGroupDictionary(data, level?){
        data.forEach((item, i) =>{
            groupDictionary[item.id] = level !== undefined? level + "-" + i : i.toString()
            deviceNodeIdGroup[item.nodeId] = []
            if(item.children && item.children.length){
                initializeTheCompanyGroupDictionary(item.children, groupDictionary[item.id])
                // 计算该组子级个数
                groupDictionary[item.id] += ("*" + item.children.length)
            }
        })
    }

    /**
     * 初始化设备的索引字典
     */
    function initializeTheDeviceDictionary(){
        data2.forEach((item) => {
            const id = item.groupId? item.groupId : item.companyId
            const g =  groupDictionary[id].split("*")
            const level = g[0], i = g[1]
            if(!(id in deviceGroup)){
                deviceGroup[id] = (i ? parseInt(i) : 0)
            }else{
                deviceGroup[id] ++
            }
            deviceGroupDict[item.imei] = level + "-" + deviceGroup[id]
            deviceNodeIdGroup[`${item.groupId? "g" : "i"}-${id}`].push(item.nodeId)
        })
    }

    return {
        deviceGroupDict,
        deviceNodeIdGroup
    }
}